#include "stdafx.h"
#if 0 
#include <ctime>
#include <iostream>
#include <string>

#include "Communicator.h"
#include "GameServer.h"

using boost::asio::ip::tcp;

tcp_server::tcp_server()
    : acceptor_(io_service, tcp::endpoint(tcp::v4(), 13))
{
    io_service.run();
    boost::thread some_thread(boost::bind(&tcp_server::start_accept, this));
}

void tcp_server::send(std::vector<unsigned char>& data)
{
#if 0 
    boost::system::error_code writeError;
    boost::asio::write(socket, boost::asio::buffer(data), writeError);
    // TODO: handle write errors
#endif 
}

void tcp_server::send(void* data, unsigned int size)
{
#if 0
    boost::system::error_code writeError;
    boost::asio::write(socket, boost::asio::buffer(data, size), writeError);
    // TODO: handle write errors
#endif 
}

void tcp_server::start_accept()
{
    std::printf("WAITING for connections\n");

    for (;;)
    {
        boost::shared_ptr<tcp::socket> socket(new tcp::socket(acceptor_.get_io_service()));
        acceptor_.accept(*socket);
        clientSockets.push_back(socket); // block or sth 
        std::printf("Added a new client\n");

        // send info from server to client


        // send an id to the client to uniquely identify it 
    }
}

void tcp_server::communicate()
{
    int anInt = 10004;
    int dataSize = sizeof(int);

    for ( unsigned int i = 0; i < clientSockets.size(); ++i )
    {
        boost::system::error_code writeError;
        boost::asio::write(*clientSockets[i], boost::asio::buffer(&dataSize, sizeof(int)), writeError);
        boost::asio::write(*clientSockets[i], boost::asio::buffer(&anInt, sizeof(int)), writeError);
        // TODO: handle writeerrors
    }
}

void tcp_server::receiveUnknown(std::vector<unsigned char>& buffer)
{
    boost::system::error_code readError;
    /* Get the size of incoming data */
    int incomingSize = -1;
    boost::asio::read(*(*socketIt), boost::asio::buffer(&incomingSize, sizeof(int)), boost::asio::transfer_all(), readError);
    /* read data */ 
    resizeIf(buffer, incomingSize);
    boost::asio::read(*(*socketIt), boost::asio::buffer(&buffer[0], incomingSize), boost::asio::transfer_all(), readError);
}

void tcp_server::receiveKnown(void* buffer, unsigned int size)
{
    boost::system::error_code readError;
    boost::asio::read(*(*socketIt), boost::asio::buffer(buffer, size), boost::asio::transfer_all(), readError);

    /*
    if (readError == boost::asio::error::eof)
        ; // TODO: handle connection reset by server 
    else if (readError)
        throw boost::system::system_error(readError); // Some other error.
    */
}

bool tcp_server::next()
{
    ++socketIt;
    return socketIt != clientSockets.end();
}
void tcp_server::reset()
{
    socketIt = clientSockets.begin();
}
#endif 